<?php

namespace Acme\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Acme\EventBundle\Entity\Information;
use Acme\EventBundle\Entity\Inscription;
use Acme\EventBundle\Entity\Feedback;
use Acme\EventBundle\Entity\Aperolocation;
use Acme\EventBundle\Entity\Statisticgroup;
use Acme\EventBundle\Entity\Statisticparameter;
use Acme\EventBundle\Entity\Statisticvalue;
use Acme\AdminBundle\Entity\Document;
use Doctrine\ORM\EntityRepository;

// these import the "@Route" and "@Template" annotations
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Validator\Constraints\DateTime;

/**
 * @Route("/auth/security/admin")
 */
class AdminController extends Controller {
	
	/**
	 * @Route("/newEvents", name="new_events")
	 * @Template()
	 */
	public function newEventsAction(Request $request) {
		$em = $this->getDoctrine ()->getManager ();
		$informations = $em->getRepository ( 'AcmeEventBundle:Information' )->findAllPersons ();
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$information = new Information ();
		
		$_information ['day'] = '';
		$_information ['month'] = '';
		$_information ['year'] = '';
		
		$form = $this->createFormBuilder ( $information )->add ( 'datum', 'date' )->add ( 'user', 'entity', array (
				'class' => 'AcmeUserBundle:User',
				'query_builder' => function (EntityRepository $er) {
					return $er->createQueryBuilder ( 'u' )->orderBy ( 'u.username', 'ASC' );
				} 
		) )->add ( 'street', 'text' )->add ( 'postcode', 'text' )->add ( 'city', 'text' )->add ( 'email', 'text' )->add ( 'telefon', 'text' )->add ( 'description', 'textarea' )->add ( 'save', 'submit', array (
				'label' => 'Erfassen' 
		) )->getForm ();
		
		$form->handleRequest ( $request );
		
		if ($form->isValid ()) {
			
			$user_id = $request->request->get ( 'form' )['user'];
			$datum = $request->request->get ( 'form' )['datum'];
			
			$event_datum = $datum ['year'];
			$event_datum .= '-';
			$event_datum .= $datum ['month'] < 10 ? '0' . $datum ['month'] : $datum ['month'];
			$event_datum .= '-';
			$event_datum .= $datum ['day'] < 10 ? '0' . $datum ['day'] : $datum ['day'];
			
			$arr_datum = explode ( '-', $event_datum );
			
			$send_datum = mktime ( 0, 0, 0, $arr_datum [1], $arr_datum [2], $arr_datum [0] );
			
			$send_datum = date ( 'Y-m-d', $send_datum - (60 * 60 * 24 * 7) );
			
			$information->setUser ( $em->getRepository ( 'AcmeUserBundle:User' )->find ( $user_id ) );
			$information->setDatum ( new \DateTime ( $event_datum ) );
			$information->setDatumSend ( new \DateTime ( $send_datum ) );
			$information->setIsSend ( 0 );
			$information->setStreet ( '' );
			$information->setPostcode ( '' );
			$information->setCity ( '' );
			$information->setEmail ( '' );
			$information->setTelefon ( '' );
			$information->setDescription ( '' );
			$information->setWebsite ( '' );
			$information->setGooglesite ( '' );
			$information->setAperolocation ( $em->getRepository ( 'AcmeEventBundle:Aperolocation' )->find ( 1 ) );
			$information->setUserIsInformed ( 0 );
			$information->setActuellInformation ( 0 );
			$information->setDatumSendExecute ( new \DateTime ( '0000-00-00' ) );
			// perform some action, such as saving the task to the database
			// echo $request->get('user'); exit;
			$em = $this->getDoctrine ()->getManager ();
			$em->persist ( $information );
			$em->flush ();
			
			return $this->redirect ( $this->generateUrl ( 'new_events' ) );
		}
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'informations' => $informations,
				'information' => $_information,
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'form' => $form->createView () 
		// 'otheruser' => $arr_data["otheruser"]
				)

		;
	}
	
	/**
	 * @Route("/editEvents/{id}", name="edit_events")
	 * @Template()
	 */
	public function editEventsAction($id = 0) {
		$em = $this->getDoctrine ()->getManager ();
		$arr_information = $em->getRepository ( 'AcmeEventBundle:Information' )->findByPerson ( $id );
		
		$arr_information ['year'] = $arr_information ['datum']->format ( 'Y' );
		$arr_information ['month'] = ( int ) $arr_information ['datum']->format ( 'm' );
		$arr_information ['day'] = ( int ) $arr_information ['datum']->format ( 'd' );
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		$form = $this->createFormBuilder ( $arr_information )->add ( 'datum', 'date' )->add ( 'user', 'entity', array (
				'class' => 'AcmeUserBundle:User',
				'query_builder' => function (EntityRepository $er) {
					return $er->createQueryBuilder ( 'u' )->orderBy ( 'u.username', 'ASC' );
				} 
		) )->add ( 'save', 'submit', array (
				'label' => 'Save' 
		) )->getForm ();
		
		$form->handleRequest ( $this->getRequest () );
		
		if ($form->isValid ()) {
			$information = $em->getRepository ( 'AcmeEventBundle:Information' )->find ( $id );
			
			$datum = $this->getRequest ()->get ( 'form' )['datum'];
			$event_datum ['year'] = $datum ['year'];
			$event_datum ['month'] = $datum ['month'] < 10 ? '0' . $datum ['month'] : $datum ['month'];
			$event_datum ['day'] = $datum ['day'] < 10 ? '0' . $datum ['day'] : $datum ['day'];
			$event_datum = mktime ( 0, 0, 0, $event_datum ['month'], $event_datum ['day'], $event_datum ['year'] );
			
			$send_datum = date ( 'Y-m-d', $event_datum - (60 * 60 * 24 * 7) );
			$event_datum = date ( 'Y-m-d', $event_datum );
			
			$information->setUser ( $em->getRepository ( 'AcmeUserBundle:User' )->find ( $this->getRequest ()->get ( 'form' )['user'] ) );
			$information->setDatum ( new \DateTime ( $event_datum ) );
			$information->setDatumSend ( new \DateTime ( $send_datum ) );
			$em->persist ( $information );
			$em->flush ();
			return $this->redirect ( $this->generateUrl ( 'new_events' ) );
		}
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'information' => $arr_information,
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'form' => $form->createView () 
		);
	}
	
	/**
	 * @Route("/removeEvents/{id}", name="remove_events")
	 * @Template()
	 */
	public function removeEventsAction($id = 0) {
		$em = $this->getDoctrine ()->getManager ();
		$information = $em->getRepository ( 'AcmeEventBundle:Information' )->find ( $id );
		$em->remove ( $information );
		$em->flush ();
		return $this->redirect ( $this->generateUrl ( 'new_events' ) );
	}
	
	/**
	 * @Route("/statisticOverview", name="statistic_overview")
	 * @Template()
	 */
	public function statisticOverviewAction() {
		
		$pagedata = $this->get ( 'common_pagedata' );
		$arr_data = $pagedata->getCommonSecurity ();
		
		
		$form_group = $this->createFormBuilder ( 
			$this->getRequest ()->get ( 'form' ) )
				->add ( 'name', 'text', array ( 'required' => true ) )
				->add ( 'save', 'button', array ( 'label' => 'Erfassen','attr' => array('class' => 'button-statistic-group btn-padding btn btn-default') ) )
				->getForm ();
		
		$form_group->handleRequest ( $this->getRequest () );

		$form_parameter = $this->createFormBuilder (
				$this->getRequest ()->get ( 'form' ) )
				->add ( 'name', 'text', array ( 'required' => true ) )
				->add ( 'save', 'button', array ( 'label' => 'Erfassen','attr' => array('class' => 'button-statistic-parameter btn-padding btn btn-default') ) )
				->getForm ();
		
		$form_parameter->handleRequest ( $this->getRequest () );
		
		$form_value = $this->createFormBuilder (
				$this->getRequest ()->get ( 'form' ) )
				->add ( 'name', 'text', array ( 'required' => true ) )
				->add ( 'value', 'integer', array ( 'required' => true ) )
				->add ( 'save', 'button', array ( 'label' => 'Erfassen','attr' => array('class' => 'button-statistic-value btn-padding btn btn-default') ) )
				->getForm ();
		
		$form_value->handleRequest ( $this->getRequest () );
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'form_group' => $form_group->createView (),
				'form_parameter' => $form_parameter->createView (),
				'form_value' => $form_value->createView ()
		);
		
	}

	/**
	 * @Route("/setStatisticGroup", name="set_statistic_group")
	 * @Template()
	 */
	public function setStatisticGroupAction() {
		
		$em = $this->getDoctrine ()->getManager ();
		$name = $this->getRequest ()->get ( 'form' )['name'];
		if($name != ''){
			$statisticgroup = new Statisticgroup();
			$statisticgroup->setName($name);
			try {
				$em->persist ( $statisticgroup );
				$em->flush ();
				$result = "Gruppe ist erfasst";
			} catch ( \Doctrine\Orm\NoResultException $e ) {
				$result = "Fehler! Gruppe ist nicht erfasst!";
			}
		} else {
			$result = "Fehler! Gruppe ist nicht erfasst!";
		}
 		return new Response(json_encode(array('response' => $result)));	
	}

	/**
	 * @Route("/setStatisticParameter", name="set_statistic_parameter")
	 * @Template()
	 */
	public function setStatisticParameterAction() {
		$em = $this->getDoctrine ()->getManager ();
		$name = $this->getRequest ()->get ( 'form' )['name'];
		if($name != ''){
			$statisticparameter = new Statisticparameter();
			$statisticparameter->setName( $name );
			$statisticparameter->setWeighting( 0 );
			try {
				$em->persist ( $statisticparameter );
				
				$em->flush ();
				$result = "Parameter ist erfasst";
			} catch ( \Doctrine\Orm\NoResultException $e ) {
				$result = "Fehler! Parameter ist nicht erfasst!";
			}
		} else {
			$result = "Fehler! Parameter ist nicht erfasst!";
		}
 		return new Response(json_encode(array('response' => $result)));	
	}
	
	
	/**
	 * @Route("/setStatisticValue", name="set_statistic_value")
	 * @Template()
	 */
	public function setStatisticValueAction() {
		$em = $this->getDoctrine ()->getManager ();
		$name = $this->getRequest ()->get ( 'form' )['name'];
		$value = $this->getRequest ()->get ( 'form' )['value'];
		if($name != '' && $value != ''){
			$statisticvalue = new Statisticvalue();
			$statisticvalue->setName( $name );
			$statisticvalue->setValue( $value );
			try {
				$em->persist ( $statisticvalue );
				$em->flush ();
				$result = "Value ist erfasst";
			} catch ( \Doctrine\Orm\NoResultException $e ) {
				$result = "Fehler! Value ist nicht erfasst!";
			}
		} else {
			$result = "Fehler! Value ist nicht erfasst!";
		}
 		return new Response(json_encode(array('response' => $result)));	
	}
	

	/**
	 * @Route("/pictureUpload", name="picture_upload")
	 * @Template()
	 */
	public function pictureUploadAction(Request $request) {
		$em = $this->getDoctrine ()->getManager ();
		$pagedata = $this->get ( 'common_pagedata' );
		
		$arr_data = $pagedata->getCommonSecurity ();
		
		$form = $this->createFormBuilder()->getForm();		
		$form->handleRequest($request);		
		
		if ($form->isValid()) {
			
			$files = $request->files->get('file');
			foreach ( $files as $file ){
				if($file->isValid()){
					$document = new Document($file);
					$em->persist ( $document );
					$em->flush ();
					$arr_response[$document->getId()] = $document->getName();
				}
			}
			return new Response(json_encode($arr_response));	
		}
		
		return array (
				'user' => $arr_data ["usr"],
				'personimagest' => $arr_data ["personimagest"],
				'personimages' => $arr_data ["personimages"],
				'persons' => $arr_data ["persons"],
				'usersinformation' => $arr_data ["usersinformation"],
				'inscriptions' => $arr_data ["inscriptions"],
				'information_datum' => $arr_data ["information_datum"],
				'form' => $form->createView()
		);
		
	}
	

	/**
	 * @Route("/pictureDelete", name="picture_delete")
	 * @Template()
	 */
	public function  pictureDeleteAction(){
 		$em = $this->getDoctrine ()->getManager ();
		
 		$id = $this->getRequest ()->get ( 'id' );
		
 		$document = $em->getRepository('AcmeAdminBundle:Document')->find($id);
		
 		// If not entity
 		if (!$document) {
 			throw $this->createNotFoundException('Unable to find this entity.');
 		} else {
 			// Remove the record...
 			$em->remove($document);
 			$em->flush();
 		}
		
		return new Response(json_encode(array('response' => '200')));
	}
	

	
	
	
	
}
